package com.meitianhui.convenitenbuy.module.home.ui.activity.web;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseWebViewActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.hyphenate.ui.ChatActivity;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.main.model.bean.HyphenateInfo;
import com.meitianhui.convenitenbuy.main.model.bean.UserToken;
import com.meitianhui.convenitenbuy.module.home.contract.EdinburghWebViewContract;
import com.meitianhui.convenitenbuy.module.home.di.DaggerHomeComponent;
import com.meitianhui.convenitenbuy.module.home.di.HomeModule;
import com.meitianhui.convenitenbuy.module.home.model.bean.OfficialStore;
import com.meitianhui.convenitenbuy.module.home.presenter.EdinburghWebViewPresenter;
import com.meitianhui.convenitenbuy.module.home.ui.activity.HomeCollectionActivity;
import com.meitianhui.convenitenbuy.module.home.ui.activity.HomeOrderActivity;
import com.meitianhui.convenitenbuy.module.home.ui.activity.NearByStoreActivity;
import com.meitianhui.convenitenbuy.module.home.ui.activity.SubmitOrderActivity;
import com.meitianhui.convenitenbuy.module.mine.model.rxbusBean.CollectStoreEventBean;
import com.meitianhui.convenitenbuy.module.order.model.bean.EmptyInfo;
import com.meitianhui.convenitenbuy.module.store.ui.activity.GroupShopCarActivity;
import com.meitianhui.convenitenbuy.module.store.ui.activity.StoreDetailActivity;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.util.BlurImageUtil;
import com.meitianhui.convenitenbuy.util.EmptyUtil;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.LogUtils;
import com.meitianhui.convenitenbuy.util.PreferenceUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.ChooseStoreDialog;
import com.meitianhui.convenitenbuy.widget.dialog.SettingStoreDialog;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.tencent.mm.opensdk.modelmsg.SendMessageToWX.Req.WXSceneSession;

/**
 * Created by Administrator on 2017/11/9.
 * 淘淘领web页面
 */

public class EdinburghWebViewActivity extends BaseWebViewActivity
        implements EdinburghWebViewContract.View {

    private HashMap<String, String> mTitleMap = new HashMap<>();    // 存放url和上一个界面的标题
    private String dataSource;      // 商品来源
    private String mGoodsCode;      //商品码
    private String mGoodsUrl;       //淘口令
    private String mTaoBaoLink;     //商品链接
    private String channelId;       // 是否是 0 元购商品

    private SettingStoreDialog mSettingStoreDialog;
    private boolean mIsSecond = false;
    private String mStoreId, mStoreName;
    private boolean isFresh = true;
    @Inject
    EdinburghWebViewPresenter presenter;
    private String mGoods_id;
    private IWXAPI wxApi;
    private String mPic_url;
    private String mainTitle;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerHomeComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
        wxApi = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID, true);
        if (!TextUtils.isEmpty(mTitle)) {
            setTbTitle(mTitle);
        }
        initData();
        EventPush();
    }

    private void EventPush() {
        Disposable subscribe = RxBus.get()
                .toFlowable(PayResultBean.class)
                .subscribe(new Consumer<PayResultBean>() {
                    @Override
                    public void accept(PayResultBean payResultBean) throws Exception {
                        if (payResultBean.result == Constants.PAY_RESULT_SUCCESS) {
                            finish();
                        } else if (payResultBean.result == Constants.PAY_RESULT_FAIL_HUIGUO
                                | payResultBean.result == Constants.PAY_RESULT_FAIL_ZIYING) {
                            finish();
                        }
                    }
                });
        mCompositeDisposable.add(subscribe);
    }

    private void initData() {
        Intent intent = getIntent();
        mIsSecond = intent.getBooleanExtra("is_second", false);
        mGoods_id = intent.getStringExtra("goods_id");
        mPic_url = intent.getStringExtra("pic_url");

        mCurrentName = "淘淘领";
        if (mIsSecond) {
            setTbMenu(R.mipmap.icon_title_share);
        } else {
            setTbMenu(R.mipmap.icon_title_detail);
        }
        mWebView.addJavascriptInterface(new MyJavaScriptInterface(this), "jsObj");//js调用安卓
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
    }

    @Override
    protected void onRefreshData() {
        isFresh = true;
    }

    @Override
    protected void isFinish() {
        back();
    }

    @Override
    protected void shareWxMini(View v) {
        if (url.contains("detail") || url.contains("publish")) {

            WXMiniProgramObject object = new WXMiniProgramObject();
            object.webpageUrl = url;
            object.userName = Constants.WX_MINI_ID;
            if (mainTitle.equals("淘淘领")) {
                object.path = "pages/buy/detail/taotaoling/taotaoling?goods_id=" + mGoods_id;
            } else if (mainTitle.equals("自营")) {
                object.path = "pages/buy/detail/selfsupport/selfsupport?goods_id=" + mGoods_id;
            } else if (mainTitle.equals("会过")) {
                object.path = "pages/buy/detail/selfEmployed/selfEmployed?goods_id=" + mGoods_id;
            }

            WXMediaMessage msg = new WXMediaMessage(object);

            msg.title = mShareTitle;
            msg.description = mShareDesc; //描述

            Observable.create(new ObservableOnSubscribe<Bitmap>() {
                @Override
                public void subscribe(@NonNull ObservableEmitter<Bitmap> e) throws Exception {
                    Bitmap bitmap = BlurImageUtil.returnBitmap(mPic_url);
                    e.onNext(bitmap);
                }
            }).subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Bitmap>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                        }

                        @Override
                        public void onNext(@NonNull Bitmap bitmap) {
                            msg.setThumbImage(bitmap);
                            SendMessageToWX.Req req = new SendMessageToWX.Req();
                            req.message = msg;
                            req.scene = WXSceneSession;
                            wxApi.sendReq(req);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                        }

                        @Override
                        public void onComplete() {
                        }
                    });
        }
    }

    @Override
    protected void clickMenu() {
        super.clickMenu();
        if (mIsSecond) {
            share(Constants.TYPE_GOOD_DETAIL_PAGE);
        } else {
            if (!InfoProvider.getLoginStatus(EdinburghWebViewActivity.this)) {
                JumpUtil.jumpToLoginActivity(0, EdinburghWebViewActivity.this, 0, "");
                return;
            }
            Intent intent = new Intent(EdinburghWebViewActivity.this, HomeOrderActivity.class);
            startActivity(intent);
        }
    }

    @Override
    protected void urlLoading(WebView view, String url) {
        view.loadUrl(url);
    }

    @Override
    protected void receivedTitle(WebView view, String title) {
        this.mainTitle = title;

        // 加载首页
        if (!mWebView.canGoBack()) {
            // 首页使用intent传递过来的标题，只有当传递过来的标题为空时，才使用网页标题
            title = TextUtils.isEmpty(mTitle) ? title : mTitle;
        } else {
            mTitleMap.put(view.getUrl(), mTb_title.getText().toString());
        }
        setTbTitle(title);
    }

    @Override
    public void showError(String msg) {
    }

    @Override
    public void loginHyphenateSuccess() {
    }

    @Override
    public void getOfficialStore(OfficialStore officialStore, String dataSourse, String value) {
        if (officialStore != null) {
            mStoreId = officialStore.getStores_id();
            mStoreName = officialStore.getStores_name();
            mSettingStoreDialog = new SettingStoreDialog(EdinburghWebViewActivity.this, R.style.dialog_with_alpha, new SettingStoreDialog.AlertDialogListener() {
                @Override
                public void onConfirmClick() {
                    mSettingStoreDialog.dismiss();

                    if ("huiguo".equals(dataSourse) | "meitianhui".equals(dataSourse)){
                        //跳到支付界面
                        Intent intent = new Intent(EdinburghWebViewActivity.this, SubmitOrderActivity.class);
                        intent.putExtra("value",value);
                        intent.putExtra("from","");
                        startActivity(intent);

                    }else {
                        //就是淘宝商品
                        presenter.officialStorePost(mStoreId, mStoreName, mGoodsCode, mGoodsUrl, channelId);
                    }
                    presenter.settingDefaultStore(mStoreId);
                }

                @Override
                public void onCancelClick() {
                    mSettingStoreDialog.dismiss();
                    if ("huiguo".equals(dataSourse) | "meitianhui".equals(dataSourse)){
                        //跳到支付界面
                        Intent intent = new Intent(EdinburghWebViewActivity.this, SubmitOrderActivity.class);
                        intent.putExtra("value",value);
                        intent.putExtra("from","");
                        startActivity(intent);

                    }else {
                        //就是淘宝商品
                        presenter.officialStorePost(mStoreId, mStoreName, mGoodsCode, mGoodsUrl, channelId);
                    }
                }
            });
            mSettingStoreDialog.show();
            mSettingStoreDialog.showCancelBtn(true);
            mSettingStoreDialog.setDialogTitle("提示");
            mSettingStoreDialog.setDialogContent("是否将此门店设为默认门店");
        }
    }

    /**
     * 提交订单
     */
    @Override
    public void officialStorePostSuccess(EmptyInfo data) {
        TipUtils.showToast(App.getInstance(), "领取成功", 1);
        RxBus.get().post(new EventBean(Constants.EVENT_TYPE_ORDER_OPERATION));
        if (!TextUtils.isEmpty(mTaoBaoLink)) {
            SystemUtils.open(EdinburghWebViewActivity.this, mTaoBaoLink, data.order_id);
        } else {
            Intent intent = new Intent(EdinburghWebViewActivity.this, HomeOrderActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void officialStorePostFail(int code, String msg) {
        TipUtils.showToast(App.getInstance(), msg);
    }

    /**
     * 设置默认门店成功
     */
    @Override
    public void settingDefaultStoreSuccess() {
        PreferenceUtils.putString(this, Constants.DEFAULT_STORE_ID, mStoreId);
        PreferenceUtils.putString(this, Constants.DEFAULT_STORE_NAME, mStoreName);
        RxBus.get().post(new CollectStoreEventBean(Constants.COLLECT_MENU_COMFIRM));
    }


    //js调用安卓代码
    private class MyJavaScriptInterface {
        private Handler handler = new Handler();
        private Context mContext;

        public MyJavaScriptInterface(Context c) {
            this.mContext = c;
        }

        //获取消费者id
        @JavascriptInterface
        public void getMemberId(String memberId) {
            UserToken userToken = InfoProvider.getUserToken(App.getInstance());
            if (userToken == null) {
                JumpUtil.jumpToLoginActivity(0, EdinburghWebViewActivity.this, 0, "");
            } else {
                mWebView.loadUrl("javascript:" + memberId + "(" + userToken.getMember_id() + ")");
            }
        }

        //获取淘宝信息
        @JavascriptInterface
        public void getTaobaoMemberName(final String taoBaoName) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    UserToken userToken = InfoProvider.getUserToken(App.getInstance());
                    if (userToken == null) {
                        JumpUtil.jumpToLoginActivity(0, EdinburghWebViewActivity.this, 0, "");
                    } else {
                        String account_id = userToken.getAccount_id();
                        String account_no = userToken.getAccount_no();
                        if ("-1".equals(account_id)) {
                            // getTaobaoMes(taoBaoName);
                            return;
                        }
                        if (TextUtils.isEmpty(account_id)) {
                            account_id = "";
                        }
                        if (TextUtils.isEmpty(account_no)) {
                            account_no = "";
                        }
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("account_id", account_id);
                            jsonObject.put("account_no", account_no);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String tempData;
                        tempData = "'" + jsonObject.toString() + "'";
                        mWebView.loadUrl("javascript:" + taoBaoName + "(" + tempData + ")");
                    }
                }
            });

        }

        //获取淘宝信息
        @JavascriptInterface
        public void bindTaobaoMemberName() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    // Intent intent = new Intent(EdinburghWebViewActivity.this, BingingTaobaoActivity.class);
                    // startActivity(intent);
                }
            });
        }

        //店东ID
        @JavascriptInterface
        public void showStore(String storeId) {
            try {
                JSONObject jsonObject = new JSONObject(storeId);
                String storesId=jsonObject.getString("stores_id");
                Intent intent = new Intent(EdinburghWebViewActivity.this, StoreDetailActivity.class);
                intent.putExtra("store_id",storesId);
                startActivity(intent);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //弹窗选择支付类型  立即领取
        @JavascriptInterface
        public void showSelectDialog(final String json) {

            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (!InfoProvider.getLoginStatus(EdinburghWebViewActivity.this)) {
                        JumpUtil.jumpToLoginActivity(0, EdinburghWebViewActivity.this, 0, "");
                        return;
                    }
                    createDialog(json);
                }
            });
        }

        //返回按钮
        @JavascriptInterface
        public void closeWebView() {
            EdinburghWebViewActivity.this.finish();
        }

        //打开淘宝
        @JavascriptInterface
        public void openTaobao(final String taokouling) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "获取淘口令：" + taokouling);
                    SystemUtils.open(App.getInstance(), taokouling);
                }
            }, 0);
        }

        @JavascriptInterface
        public void openTaobaoLink(final String taobaolink) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject jsonObject=new JSONObject(taobaolink);
                        String link=jsonObject.getString("taobao_link");
                        String product_source=jsonObject.getString("product_source");
                        if(!TextUtils.isEmpty(link)) {
                            Intent intent = new Intent(EdinburghWebViewActivity.this, AliSdkWebViewProxyActivity.class);
                            intent.putExtra("order_id", "");
                            intent.putExtra("taobao_link", link);
                            startActivity(intent);
                        }else{
                            SystemUtils.open(getApplicationContext(), product_source);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, 0);
        }

        //伙拼团跳购物车
        @JavascriptInterface
        public void buyGroupGoods(final String goodid) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(EdinburghWebViewActivity.this, GroupShopCarActivity.class);
                    intent.putExtra("invitation_code", goodid);
                    startActivity(intent);
                }
            }, 0);
        }

        //客服功能
        @JavascriptInterface
        public void chatWithCustomerServiceAgent(final String chat) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (!InfoProvider.getLoginStatus(EdinburghWebViewActivity.this)) {
                            JumpUtil.jumpToLoginActivity(0, EdinburghWebViewActivity.this, 0, "");
                            return;
                        }
                        HyphenateInfo hyphenateInfo = InfoProvider.getHyphenateInfo(EdinburghWebViewActivity.this);
                        if (hyphenateInfo == null) {
                            return;
                        }
                        String imUserId = hyphenateInfo.getIm_user_id();
                        if (TextUtils.isEmpty(imUserId)) {
                            return;
                        }
                        JSONObject jsonObject = new JSONObject(chat);
                        final String chatId = jsonObject.getString("chat_id");
                        final String title = jsonObject.getString("title");
                        Intent intent = new Intent(EdinburghWebViewActivity.this, ChatActivity.class);
                        intent.putExtra("userId", chatId);
                        intent.putExtra("groupName", title);
                        startActivity(intent);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, 0);
        }

        @JavascriptInterface
        public void share(String s_1) {
            if (!TextUtils.isEmpty(s_1)) {
                try {
                    JSONObject jsonObject = new JSONObject(s_1);
                    mShareTitle = jsonObject.getString("title");
                    mShareDesc = jsonObject.getString("desc");
                    mShareImgPath = jsonObject.getString("imgPath");
                    mShareUrl = jsonObject.getString("url");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @JavascriptInterface
        public void openMPH() {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent mIntent = new Intent(EdinburghWebViewActivity.this, BrandWebViewActivity.class);
                    mIntent.putExtra("url", Constants.HOST + "h5/c/gold-exchange"
                            + "?area_id=" + InfoProvider.getAreaCode(EdinburghWebViewActivity.this));
                    mIntent.putExtra("title", "品牌领");
                    mIntent.putExtra("type", "gold-exchange");
                    mIntent.putExtra("isgoforllm", true);
                    startActivity(mIntent);
                }
            }, 0);
        }

        //打开广告页
        @JavascriptInterface
        public void openAdLayer(final String jsonData) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "openAdLayer jsonData:" + jsonData);
                    try {
                        JSONObject jsonObject = new JSONObject(jsonData);
                        String url = jsonObject.getString("url");
                        Intent intent = new Intent(EdinburghWebViewActivity.this, AdWebViewActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });
        }
    }

    private void createDialog(String json) {
        JSONObject object = null;
        try {
            object = new JSONObject(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (object == null) {
            LogUtils.e("Wrong json data from Detail Goods Page.");
            return;
        }

        dataSource = object.optString("data_source");
        mTaoBaoLink = object.optString("taobao_link");
        mGoodsCode = object.optString("goods_code");
        mGoodsUrl = object.optString("goods_url");
        channelId = String.valueOf(object.optInt("channel_id"));

        // 有 data_source 的值。
        if (object.opt("data_source") != null) {
            if (Constants.TYPE_HUIGUO.equals(dataSource)) {
                if (EmptyUtil.isEmpty(InfoProvider.getDefaultStoreId(this))) {
                    // 如果没有默认门店的id，则按以前逻辑去弹窗，去选择门店。
                    chooseStore(json);
                } else {
                    // 如果有默认门店，直接跳到提交订单界面。
                    Intent intent = new Intent(this, SubmitOrderActivity.class);
                    intent.putExtra("value", json);
                    intent.putExtra("from", "");
                    startActivity(intent);
                }

            } else if (Constants.TYPE_MEITIANHUI.equals(dataSource)) {
                if (EmptyUtil.isEmpty(InfoProvider.getDefaultStoreId(this))) {
                    chooseStore(json);
                } else {
                    Intent intent = new Intent(this, SubmitOrderActivity.class);
                    intent.putExtra("value", json);
                    intent.putExtra("from", "");
                    startActivity(intent);
                }
            }
        }

        // 有 taobao_link 的值，是淘淘领。
        if (object.opt("taobao_link") != null) {
            if (EmptyUtil.isEmpty(InfoProvider.getDefaultStoreId(this))) {
                chooseStore(json);
            } else {
                presenter.officialStorePost(InfoProvider.getDefaultStoreId(this),
                        InfoProvider.getDefaultStoreName(this), mGoodsCode, mGoodsUrl, channelId);
            }
        }
    }

    // 显示dialog，让用户选择下单的门店。
    private void chooseStore(String json) {
        // 未登陆时。
        if (!InfoProvider.getLoginStatus(EdinburghWebViewActivity.this)) {
            JumpUtil.jumpToLoginActivity(0, EdinburghWebViewActivity.this, 0, "");
            return;
        }

        new ChooseStoreDialog(EdinburghWebViewActivity.this, new ChooseStoreDialog.DialogClick() {
            @Override
            public void collectionClick() {
                Intent intent = new Intent(EdinburghWebViewActivity.this, HomeCollectionActivity.class);
                intent.putExtra("goods_code", mGoodsCode);
                intent.putExtra("goods_url", mGoodsUrl);
                intent.putExtra("taobao_link", mTaoBaoLink);
                startActivity(intent);
            }

            @Override
            public void nearClick() {
                Intent intent = new Intent(EdinburghWebViewActivity.this, NearByStoreActivity.class);
                intent.putExtra("goods_code", mGoodsCode);
                intent.putExtra("goods_url", mGoodsUrl);
                intent.putExtra("taobao_link", mTaoBaoLink);
                startActivity(intent);
            }

            @Override
            public void officialClick() {
                // fixme : 如果是 taoBaoLink 时， dataSource / json 传入是空字符串。
                presenter.getOfficialStore(mGoodsCode, mGoodsUrl, mTaoBaoLink, dataSource, json);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void back() {
        isFresh = false;
        if (mWebView.canGoBack() && !"about:blank".equals(mWebView.getUrl())) {
            String currentUrl = mWebView.getUrl();
            if (mTitleMap.isEmpty() || TextUtils.isEmpty(mTitleMap.get(currentUrl))) {
            } else {
                mTitleMap.remove(currentUrl);
            }
            mWebView.goBack();
        } else {
            finish();
            mTitleMap.clear();
        }
    }

}
